/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import entity.Result;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 *
 * @author Young Ran
 */
public class ResultDAO {
    
    private Connection cn;
    private PreparedStatement pstm;
    private CallableStatement cs;
    
    public ResultDAO() {
        cn = DB_Util.getConnection();
    }
    
    private ArrayList getResultData(ResultSet rs) throws SQLException {
        ArrayList list = new ArrayList();
        while (rs.next()) {
            Result e = new Result();
            e.setId(rs.getInt("ResultId"));
            e.setMark(rs.getInt("ResultMark"));
            e.setComment(rs.getString("ResultComment"));
            e.setFitnessProgramsId(rs.getInt("FitnessProgramId"));
            e.setUserDetailsId(rs.getInt("UserDetailId"));
            e.setStatus(rs.getInt("status"));
            list.add(e);
        }
        return list;
    }
    
    //DISPLAY RESULT:
    public ArrayList getAllResult() throws SQLException {
        cs = cn.prepareCall("{call SP_Display_Result}");
        ResultSet rs = cs.executeQuery();
        return getResultData(rs);
    }
    public ArrayList getResultById(int id) throws SQLException {
        cs = cn.prepareCall("{call SP_Display_Result_ById(?)}");
        cs.setInt(1, id);
        ResultSet rs = cs.executeQuery();
        return getResultData(rs);
    }
    public void addResult(Result item) throws SQLException
    {
        cs = cn.prepareCall("{call SP_Add_Result(?,?,?,?)}");
        cs.setInt(1, item.getMark());
        cs.setNString(2, item.getComment());
        cs.setInt(3, item.getFitnessProgramsId());
        cs.setInt(4, item.getUserDetailsId());
        cs.execute();
    }
    
    public ArrayList<Result> getAllUnapprovedResult() throws SQLException {
        cs = cn.prepareCall("{call SP_Display_UnapprovedResult}");
        ResultSet rs = cs.executeQuery();
        return getResultData(rs);
    }
    
    public void approveResult(int resultId) throws SQLException
    {
        cs = cn.prepareCall("{call SP_Approve_Result(?)}");
        cs.setInt(1, resultId);
        cs.execute();
    }
    
    public void editResult(Result item) throws SQLException
    {
        cs = cn.prepareCall("{call SP_Edit_Result(?,?,?)}");
        cs.setInt(1, item.getId());
        cs.setInt(2, item.getMark());
        cs.setNString(3, item.getComment());
        cs.execute();
    }     
}
